package com.bolt.support.sqlconfig.base;

import com.bolt.convention.exception.ServiceException;
import com.bolt.common.ognl.OgnlCache;
import ognl.OgnlException;

import java.math.BigDecimal;
import java.util.Arrays;

public class ExpressionEvaluator {



	public boolean evaluateBoolean(String expression, Object parameterObject) {
		try {
			if(null == parameterObject){
				return false;
			}
			Object value = OgnlCache.getValue(expression, parameterObject);
			if (value instanceof Boolean){
                return (Boolean) value;
            }

			if (value instanceof Number){
                return !new BigDecimal(String.valueOf(value)).equals(BigDecimal.ZERO);
            }

			return value != null;
		} catch (Exception e) {
			throw new ServiceException("Error evaluating expression '"
					+ expression + "'. Cause: " + e, e);
		}
	}

	@SuppressWarnings("rawtypes")
	public Iterable evaluateIterable(String expression, Object parameterObject) {
		try {
			Object value = OgnlCache.getValue(expression, parameterObject);
			if (value == null) {
                throw new ServiceException("The expression '" + expression + "' evaluated to a null value.");
            }
			if (value instanceof Iterable){
				return (Iterable) value;
            }
			if (value.getClass().isArray()) {
                return Arrays.asList((Object[]) value);
            }
			throw new ServiceException("Error evaluating expression '"+ expression + "'.  Return value (" + value+ ") was not iterable.");
		} catch (OgnlException e) {
			throw new ServiceException("Error evaluating expression '"
					+ expression + "'. Cause: " + e, e);
		}
	}

}
